<?php

namespace App\Models;

use Encore\Admin\Auth\Database\Role;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis;

class User extends Authenticatable
{
    use Notifiable;
    protected $table = 'admin_users';
    protected $fillable = [
        'name', 'email', 'password',
    ];
    protected $hidden = [
        'password', 'remember_token',
    ];
    protected $casts = [
        'email_verified_at' => 'datetime',
    ];

    // region 关系关联
    /**
     * @return mixed 呼叫记录
     */
    public function call_record()
    {
        return $this->hasMany(ClientCallRecord::class, 'employee_id', 'id');
    }

    public static function getAll()
    {
        return self::query()->where('id','>',1)->get();
    }

    /**
     * 呼叫统计
     */
    public function calls()
    {
        return $this
            ->hasMany(ClientCallRecord::class,'employee_id','id')
            ->where('call_type',1);
    }

    /**
     * 接听统计
     */
    public function answers()
    {
        return $this
            ->hasMany(ClientCallRecord::class,'employee_id','id')
            ->where('call_type',2);
    }

    /**
     * 所属部门
     * @return \Illuminate\Database\Eloquent\Relations\BelongsTo
     */
    public function departments()
    {
        return $this->belongsTo(Department::class,'department_id','id');
    }

    /**
     * 权证人
     * @return \Illuminate\Database\Eloquent\Relations\HasMany
     */
    public function helpers()
    {
        return $this->hasMany(NeedHelp::class, 'employee_id','id');
    }

    public function needHelpers()
    {
        return $this->hasMany(NeedHelp::class,'helper_id','id');
    }

    /**
     * 跟进记录
     * @return \Illuminate\Database\Eloquent\Relations\HasMany
     */
    public function records()
    {
        return $this->hasMany(ClientRecords::class,'employee_id','id');
    }

    /**
     * 已跟进的客户
     */
    public function followed(){
        return $this->hasMany(ClientRecords::class,'employee_id','id')->groupBy('client_id')->count('client_id');
    }

    /**
     * 放出贷款
     * @return \Illuminate\Database\Eloquent\Relations\HasMany
     */
    public function moneyOut()
    {
        return $this->hasMany(MoneyOut::class,'employee_id','id');
    }

    /**
     * 拥有客户
     */
    public function clients()
    {
        return $this->hasMany(Client::class, 'employee_id','id');
    }

    /**
     * A user has and belongs to many roles.
     *
     * @return BelongsToMany
     */
    public function roles(): BelongsToMany
    {
        $pivotTable = config('admin.database.role_users_table');

        $relatedModel = config('admin.database.roles_model');

        return $this->belongsToMany($relatedModel, $pivotTable, 'user_id', 'role_id');
    }

    /**
     * A User has and belongs to many permissions.
     *
     * @return BelongsToMany
     */
    public function permissions(): BelongsToMany
    {
        $pivotTable = config('admin.database.user_permissions_table');

        $relatedModel = config('admin.database.permissions_model');

        return $this->belongsToMany($relatedModel, $pivotTable, 'user_id', 'permission_id');
    }

    //endregion

    /**
     * 格式化ID
     * @param $id
     * @param bool $name
     * @return string
     */
    public static function myTitle($id,$name=true)
    {
        $cacheFile = date('Ymd',time()).'-myTitle-$name-'.$id;
        if(Redis::exists($cacheFile)) {
            $r_data = Redis::get($cacheFile);
        }else{
            $me = self::query()->where('id',$id)->with('departments')->first();
            $current_part = isset($me->departments->title) ? $me->departments->title : '';
            $secDep ='';
            if(isset($me->departments->parent_id) && $me->departments->parent_id > 0){
                $secDep = Department::allDepartment()[$me->departments->parent_id].' &nbsp;&nbsp;>&nbsp;';
            }
            $myname = $name ? $me->name.'<br/>' : '';
            $r_data = "$myname $secDep $current_part ";
            Redis::set($cacheFile,$r_data);
        }
        return $r_data;
    }

    public static function myDepartment($id)
    {
        $cacheFile = date('Ymd',time()).'-myDepartment-'.$id;
        if(Redis::exists($cacheFile)) {
            $r_data = Redis::get($cacheFile);
        }else{
            $me = self::query()->where('id',$id)->with('departments')->first();
            $current_part = isset($me->departments->title) ? $me->departments->title : '';
            $secDep ='';
            if(isset($me->departments->parent_id) && $me->departments->parent_id > 0){
                $secDep = Department::allDepartment()[$me->departments->parent_id].' &nbsp;&nbsp;>&nbsp;';
            }
            $r_data = " $secDep $current_part ";
            Redis::set($cacheFile,$r_data);
        }
        return $r_data;
    }

    public static function deDepartment($id)
    {
        $cacheFile = date('Ymd',time()).'-deDepartment-'.$id;
        if(Redis::exists($cacheFile)) {
            $r_data = Redis::get($cacheFile);
        }else{
            $de = Department::query()->where('id',$id)->first();
            $current_part = isset($de->title) ? $de->title : '';
            $secDep ='';
            if(isset($de->parent_id) && $de->parent_id > 0){
                $secDep = Department::allDepartment()[$de->parent_id].' &nbsp;&nbsp;>&nbsp;';
            }
            $r_data = " $secDep $current_part ";
            Redis::set($cacheFile,$r_data);
        }
        return $r_data;
    }

    /**
     * 全部员工
     * @return mixed
     */
    public static function Users()
    {
        $cacheFile = date('Ymd',time()).'-Users-';

        if(Redis::exists($cacheFile)) {
            $r_data = Redis::get($cacheFile);
        }else{
            $users = DB::table('admin_users')
                ->where('id','>',1)
                ->pluck('name', 'id')->toArray();
            $r_data = json_encode($users);
            Redis::set($cacheFile,$r_data);
        }

        return json_decode($r_data, true);
    }

    /**
     * 加入部门
     * @param $department_id
     * @param $employee_ids
     * @return int
     */
    public static function joinDepartment($department_id, $employee_ids)
    {
        return self::query()->whereIn('id',$employee_ids)->update(['department_id'=>$department_id]);
    }


    /**
     * 退出部门
     * @param $employee_ids
     * @return int
     */
    public static function quitDepartment($employee_ids)
    {
        return self::query()->whereIn('id',$employee_ids)->update(['department_id'=>NULL]);
    }

}
